using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UI_SkillTreeSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, ISaveManager
{
    private UI ui;
    private Image skillImage;

    // 技能解锁需花费的价格
    [SerializeField] private int skillPrice;

    // 序列化字段，私有变量，用于存储技能名称和描述
    [SerializeField] private string skillName;
    [TextArea]
    [SerializeField] private string skillDescription;

    // 序列化字段，私有变量，用于存储锁定技能的颜色
    [SerializeField] private Color lockedSkillColor;

    // 公共变量，表示技能是否已解锁
    public bool unlocked;

    // 序列化字段，私有变量，用于存储前置技能
    [SerializeField] private UI_SkillTreeSlot[] shouldBeUnlocked;
    // 序列化字段，私有变量，用于存储同等级技能
    [SerializeField] private UI_SkillTreeSlot[] shouldBeLocked;

    // 在编辑器中验证时调用，设置对象名称
    private void OnValidate()
    {
        gameObject.name = "SkillTreeSlot - " + skillName;
    }

    private void Awake()
    {
        GetComponent<Button>().onClick.AddListener(() => UnlockSkillSlot());
        // 因为执行顺序问题无法解锁技能就放这里
    }

    // 初始化方法
    private void Start()
    {
        skillImage = GetComponent<Image>();
        ui = GetComponentInParent<UI>();
        skillImage.color = lockedSkillColor;
        // GetComponent<Button>().onClick.AddListener(() => UnlockSkillSlot());
        if (unlocked)
            skillImage.color = Color.white;
    }

    // 解锁技能槽
    public void UnlockSkillSlot()
    {
        if (unlocked) return;
        if (!PlayerManager.instance.HaveEnoughMoney(skillPrice))
        {
            return;
        }
        // 遍历前置技能是否已解锁
        for (int i = 0; i < shouldBeUnlocked.Length; i++)
        {
            if (shouldBeUnlocked[i].unlocked == false)
            {
                return;
            }
        }
        // 遍历同等级的其他技能，限制技能解锁
        for (int i = 0; i < shouldBeLocked.Length; i++)
        {
            if (shouldBeLocked[i].unlocked == true)
            {
                return;
            }
        }
        unlocked = true;
        skillImage.color = Color.white;
    }

    // 当鼠标指针进入时调用，显示技能提示
    public void OnPointerEnter(PointerEventData eventData)
    {
        ui.skillToopTip.ShowToolTip(skillDescription, skillName, skillPrice);
    }

    // 当鼠标指针退出时调用，隐藏技能提示
    public void OnPointerExit(PointerEventData eventData)
    {
        ui.skillToopTip.HideToolTip();
    }

    public void LoadData(GameData _data)
    {
        if (_data.skillTree.TryGetValue(skillName, out bool value))
        {
            unlocked = value;
        }
    }

    public void SaveData(ref GameData _data)
    {
        if (_data.skillTree.TryGetValue(skillName, out bool value))
        {
            _data.skillTree.Remove(skillName);
            _data.skillTree.Add(skillName, unlocked);
        }
        else
        {
            _data.skillTree.Add(skillName, unlocked);
        }
    }
}